BUILD:=./build

CFLAGS:= -m32
CFLAGS+= -masm=intel
CFLAGS+= -fno-builtin
CFLAGS+= -nostdinc
CFLAGS+= -fno-pic
CFLAGS+= -fno-pie
CFLAGS+= -nostdlib
CFLAGS+= -fno-stack-protector
CFLAGS+= -I./oskernel/include
CFLAGS:=$(strip ${CFLAGS})

CFLAGS64:= -m64
CFLAGS64+= -mcmodel=large
CFLAGS64+= -fno-builtin
CFLAGS64+= -nostdinc
CFLAGS64+= -fno-pic
CFLAGS64+= -fno-pie
CFLAGS64+= -nostdlib
CFLAGS64+= -fno-stack-protector


DEBUG:= -g

HD_IMG_NAME:="hd.img"

all: $(BUILD)/boot/boot.bin $(BUILD)/boot/setup.bin $(BUILD)/system.bin
	$(shell rm -rf $(BUILD)/$(HD_IMG_NAME))
	bximage -q -hd=16 -func=create -sectsize=512 -imgmode=flat $(BUILD)/$(HD_IMG_NAME)
	dd if=${BUILD}/boot/boot.bin of=$(BUILD)/$(HD_IMG_NAME) bs=512 seek=0 count=1 conv=notrunc
	dd if=${BUILD}/boot/setup.bin of=$(BUILD)/$(HD_IMG_NAME) bs=512 seek=1 count=2 conv=notrunc
	dd if=${BUILD}/system.bin of=$(BUILD)/$(HD_IMG_NAME) bs=512 seek=3 count=30 conv=notrunc

# 下面是32位内核用的
${BUILD}/system.bin: ${BUILD}/kernel.bin
	objcopy -O binary ${BUILD}/kernel.bin ${BUILD}/system.bin
	nm ${BUILD}/kernel.bin | sort > ${BUILD}/system.map

${BUILD}/boot/head.o: oskernel/boot/head.asm
	nasm -f elf32 -g $< -o $@

${BUILD}/boot/%.bin: oskernel/boot/%.asm
	$(shell mkdir -p ${BUILD}/boot)
	nasm $< -o $@

${BUILD}/init/main.o: oskernel/init/main.c
	$(shell mkdir -p ${BUILD}/init)
	gcc ${CFLAGS} ${DEBUG} -c $< -o $@

$(BUILD)/kernel/asm/%.o: oskernel/kernel/asm/%.S
	$(shell mkdir -p ${BUILD}/kernel/asm)
	gcc ${CFLAGS} ${DEBUG} -c $< -o $@

${BUILD}/kernel/chr_drv/console.o: oskernel/kernel/chr_drv/console.c
	$(shell mkdir -p ${BUILD}/kernel/chr_drv)
	gcc ${CFLAGS} ${DEBUG} -c $< -o $@

${BUILD}/kernel/%.o: oskernel/kernel/%.c
	$(shell mkdir -p ${BUILD}/kernel)
	gcc ${CFLAGS} ${DEBUG} -c $< -o $@

${BUILD}/lib/%.o: oskernel/lib/%.c
	$(shell mkdir -p ${BUILD}/lib)
	gcc ${CFLAGS} ${DEBUG} -c $< -o $@

${BUILD}/kernel.bin: ${BUILD}/boot/head.o ${BUILD}/init/main.o \
	${BUILD}/kernel/chr_drv/console.o $(BUILD)/kernel/asm/io.o \
	${BUILD}/kernel/printk.o ${BUILD}/kernel/vsprintf.o ${BUILD}/lib/string.o
	ld -m elf_i386 $^ -o $@ -Ttext 0x1200

qemu: all
	qemu-system-x86_64 \
	-m 32M \
	-boot c \
	-cpu Haswell -smp cores=1,threads=2 \
	-hda ./build/hd.img

qemug: all
	qemu-system-x86_64 \
	-m 32M \
	-boot c \
	-cpu Haswell -smp cores=1,threads=2 \
	-hda ./build/hd.img -s -S

clean:
	rm -rf ${BUILD}/*